package com.flyme.module.base.provider.apiPc;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.flyme.common.core.model.ResultBody;
import com.flyme.common.core.model.query.CriteriaQuery;
import com.flyme.common.core.model.query.PagerInfo;
import com.flyme.common.core.model.query.PqGrid;
import com.flyme.common.core.security.OpenHelper;
import com.flyme.common.core.security.OpenUserAuth;
import com.flyme.common.core.utils.ApiAssert;
import com.flyme.common.core.utils.DesUtils;
import com.flyme.common.core.utils.Md5Sign;
import com.flyme.common.core.utils.ObjectUtils;
import com.flyme.core.base.supper.controller.BaseController;
import com.flyme.core.base.supper.entity.EntityMap;
import com.flyme.module.base.client.entity.*;
import com.flyme.module.base.provider.qrcode.ZXingCode;
import com.flyme.module.base.provider.service.*;
import com.flyme.module.file.client.entity.SysCourse;
import com.flyme.module.file.client.entity.SysCourseType;
import com.flyme.module.file.client.entity.SysLive;
import com.flyme.module.file.provider.service.*;
import com.flyme.module.order.client.entity.Order;
import com.flyme.module.order.client.enums.OrderStatusEnum;
import com.flyme.module.order.provider.service.OrderService;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 不需要登录鉴权额接口管理
 *
 * @author flyme
 */
@Slf4j
@Api(tags = "无需鉴权接口")
@RestController
@RequestMapping("/common/pc")
public class PcApiLoginController extends BaseController<SysUserService, SysUser> {

    @Autowired
    private SysHtmlService htmlService;
    @Autowired
    private SysCourseTypeService coursetypeService;
    @Autowired
    private SysOffCourseService offcourseService;
    @Autowired
    private SysLecturerService lecturerService;
    @Autowired
    private SysCourseEnrollService courseapplyService;
    @Autowired
    private SysColleconService colleconService;
    @Autowired
    private SysCourseService courseService;
    @Autowired
    private SysSliderService sliderService;
    @Autowired
    private SysLiveService liveService;
    @Autowired
    private SysConfigService configservice;
    @Autowired
    private SysCataLogService catalogService;
    @Autowired
    private SysCourseCommentService commentService;
    @Autowired
    private SysVipService vipService;
    @Autowired
    private SysHistoryService historyService;
    @Autowired
    private SysVipconfigService vipconfigService;
    @Autowired
    private SysVipTypeService vipTypeService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private SysUserService userService;
    @Autowired
    private SysOffCourseService offCourseService;
    @Autowired
    private SysCourseEnrollService courseEnrollService;
    @Autowired
    private SysQuestionService questionService;
    @Autowired
    private SysMessageService messageService;


    /**
     * yes
     * 订单支付完成查询页面
     * type：1购买课程2购买人才测评3直播报名4充值5vip购买6线下报名
     * applyType：1安卓2ios
     */
    @PostMapping(value = "/orderSuccess")
    public ResultBody orderSuccess(String orderId) {
        EntityMap map = new EntityMap();
        Order order = orderService.getById(orderId);
        map.put("order", order);
        Long userId = order.getUserId();
        SysUser user = userService.getById(userId);
        String mobile = user.getMobile();
        map.put("mobile", mobile);
        return ResultBody.success(map);
    }

    /**
     * 获取服务协议
     */
    @GetMapping(value = "/getHtmlWeb")
    public ResultBody getHtml(String type) {
        EntityMap map = new EntityMap();
        ApiAssert.notNull("参数不能为空", type);
        SysHtml html = htmlService.findByHtmlKey(type);
        map.put("html", html);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 获取评论
     */
    @PostMapping(value = "/getReplysWeb")
    public ResultBody getReplysWeb(Long courseId, PagerInfo pagerInfo) {
        Long accountInfoId = null;
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if (ObjectUtils.isNotEmpty(openUserAuth)) {
            accountInfoId = openUserAuth.getUserId();
        }
        EntityMap detail = new EntityMap();
        Integer replyNum = commentService.firstCommentNum(courseId);
        detail.put("replyNum", replyNum);
        List<EntityMap> replysOne = commentService.selectByCourse(courseId.toString(), pagerInfo, 1);// 课程的一级评论
        for (EntityMap one : replysOne) {
            one.put("nickName", Convert.unicodeToStr(one.get("nickName")));
            one.put("commentContent", Convert.unicodeToStr(one.get("commentContent")));
            //one.put("createDate", DateUtil.getDateTime(one.get("createDate"), DateUtil.MM月dd日HHmm));
            one.put("createDate", one.get("createDate"));
            // 查询用户是否点赞
            one.put("isThumbs", 0);
            if (ObjectUtils.isNotEmpty(accountInfoId)) {
                Long id = one.get("id");
                Integer isThumbs = colleconService.isCollecon(id, accountInfoId, 3, 2);
                one.put("isThumbs", isThumbs);
            }
            List<EntityMap> replysTwo = commentService.selectByCourse2(one.get("id").toString(), pagerInfo, 2, String.valueOf(accountInfoId));// 一级评论的二级级评论
            for (EntityMap two : replysTwo) {
                //two.put("createDate", DateUtil.getDateTime(two.get("createTime"), DateUtil.MM月dd日HHmm));
                two.put("commentContent", Convert.unicodeToStr(two.get("commentContent")));
                two.put("nickName", Convert.unicodeToStr(two.get("nickName")));
                two.put("createDate", two.get("createTime"));
            }
            one.put("replysTwo", replysTwo);
            Integer thumbs = colleconService.countByTarget(one.get("id").toString(), 2);
            one.put("thumbs", thumbs);
        }
        detail.put("replys", replysOne);
        return ResultBody.success(detail);
    }


    /**
     * yes
     * 线下课程列表
     */
    @RequestMapping(value = "/offlineCourseListWeb")
    public ResultBody offlineCourseListWeb(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid pq = offcourseService.selectofflineCourseWeb(pagerInfo);
        map.put("list", pq);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 线下课程详情
     */
    @RequestMapping(value = "/offlineCourseDetailWeb")
    public ResultBody offlineCourseDetailWeb(Long courseId, String url) {
        ApiAssert.notNull("参数不能为空", courseId);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = offCourseService.getEntityMap(q().eq("id", courseId));
        Date deadline = map.get("deadline");
        Integer applyNum = courseEnrollService.applyNum(courseId,3);
        map.put("isApply", 0);//用户是否已经报名（0未报名1已报名）
        map.put("userId", "");
        if (ObjectUtils.isNotEmpty(openUserAuth)) {
            Long userId = openUserAuth.getUserId();
            Integer isApply = courseEnrollService.isApply(courseId, userId, 3);
            map.put("isApply", isApply);//用户是否已经报名（0未报名1已报名）
            map.put("userId", userId);
        }
        map.put("courseId", courseId);
        if (ObjectUtils.isEmpty(map.get("enrollNum"))) {
            map.put("enrollNum", 0);
        }
        map.put("applyNum", applyNum);//已报名人数
        Integer applyType = map.get("applyType");
        if (DateUtil.date().after(deadline)) {
            applyType = 0;
        }
        map.put("applyType",applyType);//是否截至
        SysConfig config = configservice.getByName("iosRatio");
        BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
        BigDecimal price = new BigDecimal(map.get("coursePrice").toString());
        map.put("iosPrice", price.multiply(iosRatio).setScale(0, BigDecimal.ROUND_UP));
        //微信二维码分享
        String QRCode = ZXingCode.getLogoQRCode(url, "", "");
        map.put("QRCode", QRCode);
        String offCourseContent = map.get("courseContent");
        String content = offCourseContent.replaceAll("<[.[^>]]*>", "").replaceAll("&nbsp;", "");
        if (content.length() > 100) {
            content = content.substring(0, 100) + "...";
        }
        map.put("content", content);
        map.put("urlShare", url);
        return ResultBody.success(map);
    }


    /**
     * yes
     * 根据课程查询课程类别
     */
    @RequestMapping(value = "/coursetypeWeb")
    public ResultBody coursetypeWeb(String courseId) {
        ApiAssert.notNull("参数不能为空", courseId);
        EntityMap map = new EntityMap();
        SysCourse course = courseService.getById(courseId);
        SysCourseType coursetypeSecond = coursetypeService.getById(course.getCourseTypeId());
        SysCourseType coursetypeFirst = coursetypeService.getById(coursetypeSecond.getParentId());
        map.put("coursetypeFirst", coursetypeFirst);
        map.put("coursetypeSecond", coursetypeSecond);
        return ResultBody.success(map);
    }


    /**
     * yes
     * 推荐课程列表
     * sort值：S0 全部;S1 免费;S2 VIP;S3 价格升序; S4 价格降序;
     */
    @RequestMapping(value = "/recommendListWeb")
    public ResultBody recommendListWeb(String sortOrder, PagerInfo pagerInfo) {
        ApiAssert.notNull("参数不能为空", sortOrder);
        EntityMap map = new EntityMap();
        SysCourseType coursetypeFirst = new SysCourseType();
        coursetypeFirst.setCourseTypeName("推荐课程");
        map.put("coursetypeSecond", "");
        map.put("coursetypeFirst", coursetypeFirst);
        SysConfig config = configservice.getByName("iosRatio");
        BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
        PqGrid pq = courseService.selectCourseRecommendsWeb(iosRatio, pagerInfo, sortOrder);
        map.put("lists", pq);//课程列表
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }

    /**
     * yes
     * 全部课程列表
     * sort值：S0 全部;S1 免费;S2 VIP;S3 价格升序; S4 价格降序;
     */
    @RequestMapping(value = "/courseAllWeb")
    public ResultBody courseAllWeb(String sortOrder, PagerInfo pagerInfo) {
        ApiAssert.notNull("参数不能为空", sortOrder);
        EntityMap map = new EntityMap();
//        SysCourseType coursetypeFirst = new SysCourseType();
//        coursetypeFirst.setCourseTypeName("全部课程");
        map.put("coursetypeSecond", "");
        map.put("coursetypeFirst", "");
        SysConfig config = configservice.getByName("iosRatio");
        BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
        PqGrid pq = courseService.selectCourseAllWeb(iosRatio, pagerInfo, sortOrder);
        map.put("lists", pq);//课程列表
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }

    /**
     * yes
     * 根据一级课程类别查询课程列表
     * sort值：S0 全部;S1 免费;S2 VIP;S3 价格升序; S4 价格降序;
     */
    @RequestMapping(value = "/courseListFirstWeb")
    public ResultBody courseListFirstWeb(String coursetypeId, String sortOrder, PagerInfo pagerInfo) {
        ApiAssert.notNull("参数不能为空", coursetypeId, sortOrder);
        EntityMap map = new EntityMap();
        SysCourseType coursetypeFirst = coursetypeService.getById(coursetypeId);
        map.put("coursetypeFirst", coursetypeFirst);
        map.put("coursetypeSecond", "");
        List<Map<String, Object>> parenttypes = coursetypeService.selectTypeByParent(coursetypeId);
        List<Object> ids = new ArrayList<>();
        for (Map<String, Object> coursetype : parenttypes) {
            ids.add(coursetype.get("id"));
        }
        PqGrid pq = courseService.selectCourseByTypeFirstWeb(pagerInfo, ids, sortOrder);
        map.put("lists", pq);//课程列表
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }


    /**
     * yes
     * 根据二级课程类别查询课程列表
     * sort值：S0 全部;S1 免费;S2 VIP;S3 价格升序; S4 价格降序;
     */
    @RequestMapping(value = "/courseListWeb")
    public ResultBody courseListWeb(String coursetypeId, String sortOrder, PagerInfo pagerInfo) {
        ApiAssert.notNull("参数不能为空", coursetypeId, sortOrder);
        EntityMap map = new EntityMap();
        SysCourseType coursetypeSecond = coursetypeService.getById(coursetypeId);
        SysCourseType coursetypeFirst = coursetypeService.getById(coursetypeSecond.getParentId());
        map.put("coursetypeSecond", coursetypeSecond);
        map.put("coursetypeFirst", coursetypeFirst);
        PqGrid pq = courseService.selectCourseByTypeWeb(pagerInfo, coursetypeId, sortOrder);
        map.put("lists", pq);//课程列表
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }

    /**
     * yes
     * 手机号加密
     */
    @RequestMapping(value = "/getMobile")
    public ResultBody getMobile(String mobile) {
        // 手机号
        String str_tel = mobile;
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmm");//设置日期格式
        String str_time = df.format(DateUtil.date());
        DesUtils.DESIV = DesUtils.getiv(str_time);
        String key1 = DesUtils.getkey(str_time);
        String content = DesUtils.encode(key1, str_tel);
        EntityMap map = new EntityMap();
        map.put("mobile", content);
        map.put("time", str_time);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 轮播图
     */
    @RequestMapping(value = "/slidersWeb")
    public ResultBody slidersWeb() {
        EntityMap map = new EntityMap();
        List<SysSlider> sliders = sliderService.selectSliders(1, 2);
        map.put("sliders", sliders);
        return ResultBody.success(map);
    }

    /**
     * yes
     * PC广告图
     * sliderType：轮播图类型1app,2pc首页轮播图,3APP启动图，4pc人才测评，5pc学分转换，6pc关于我们，7pc新闻中心，8pc帮助中心
     */
    @RequestMapping(value = "/sliderPC")
    public ResultBody sliderPC(Integer sliderType) {
        EntityMap map = new EntityMap();
        SysSlider slider = sliderService.selectOne(1,sliderType);
        map.put("slider", slider);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 首页
     */
    @RequestMapping(value = "/indexWeb")
    public ResultBody indexWeb(PagerInfo pagerInfo) {
//        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        //前台传过来的pagerInfo是新闻列表的。这里生成的otherPager是直播，线下课，使用的。
        PagerInfo otherPager = new PagerInfo();
        otherPager.setPageNumber(1);
        otherPager.setPageSize(8);
        List<EntityMap> lives = liveService.selectLiveWeb(otherPager,1);//在线直播
        List<EntityMap> offcourses = offcourseService.selectLiveCourseWeb(otherPager);//线下课程
        List<EntityMap> courses = courseService.selectInderCourseWeb(12);
        List<EntityMap> news = getNews(pagerInfo).getRows();
        map.put("courses", courses);
        map.put("newses", news);
        map.put("lives", lives);
        map.put("offcourses", offcourses);
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }

    /**
     * yes
     * 首页讲师推荐随机4个导师
     */
    @RequestMapping(value = "/indexLecturers")
    public ResultBody indexLecturers(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid pq = lecturerService.selectIndexLecturersWeb(pagerInfo);//为你推荐-讲师
        map.put("lecturers", pq);
        return ResultBody.success(map);
    }
    /**
     * yes
     * 推荐讲师查询
     */
    @RequestMapping(value = "/lecturersList")
    public ResultBody lecturersList(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid pq = lecturerService.selectLecturersWeb(pagerInfo);//为你推荐-讲师
        map.put("lecturers", pq);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 直播列表
     */
    @RequestMapping(value = "/liveListWeb")
    public ResultBody liveListWeb(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid pq = liveService.selectLiveListWeb(1, pagerInfo);
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        map.put("list", pq);
        return ResultBody.success(map);
    }

    /**
     * yes
     * 直播详情
     */
    @RequestMapping(value = "/liveDetailWeb")
    public ResultBody liveDetailWeb(String liveId, String url) {
        ApiAssert.notNull("参数不能为空", liveId);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        EntityMap map = new EntityMap();
        SysLive live = liveService.getById(liveId);
        //是否是vip
        map.put("isVip", 0);
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        map.put("isApply", 0);//用户是否已经报名（0未报名1已报名）
        map.put("isCollecon", 0);//用户是否收藏（0未收藏1已收藏）
        String liveUrl ="";
        if (ObjectUtils.isNotEmpty(openUserAuth)) {
            Long userId = openUserAuth.getUserId();
            Integer isApply = courseapplyService.isApply(live.getId(), userId, 2);
            if (isApply == 0) {//未购买
                Integer vip = vipService.isVip(openUserAuth.getUserId());
                //判断是否是VIP
                if (vip > 0) {
                    Integer vipFree = live.getIsVipFree();
                    if (vipFree.equals(0)) {
                        isApply = 1;
                    }
                }
            } else {
                isApply = 1;
            }
            map.put("isApply", isApply);//用户是否已经报名（0未报名1已报名）
            //是否收藏
            Integer isCollecon = colleconService.isCollecon(live.getId(), userId, 2, 1);
            map.put("isCollecon", isCollecon);//用户是否收藏（0未收藏1已收藏）
            liveUrl = Md5Sign.getUrl(userId, live.getChannelId());
        }
        live.setLiveUrl(liveUrl);
        map.put("list", live);//直播详情
        SysLecturer lecturer = lecturerService.getById(live.getLecturerId());
        if(ObjectUtils.isNotEmpty(lecturer)) {
            map.put("lecturer", lecturer);//讲师
        }else{
            map.put("lecturer",new SysLecturer());
        }
        //微信二维码分享
        String QRCode = ZXingCode.getLogoQRCode(url, "", "");
        map.put("QRCode", QRCode);
        String livecontent = live.getLiveContent();
        String content = livecontent.replaceAll("<[.[^>]]*>", "").replaceAll("&nbsp;", "");
        if (content.length() > 100) {
            content = content.substring(0, 100) + "...";
        }
        map.put("content", content);
        map.put("urlShare", url);
        SysConfig config = configservice.getByName("iosRatio");
        BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
        //推荐课程
        if (ObjectUtils.isNotNull(lecturer)) {
            List<EntityMap> recommends = courseService.selectLecturerRecommends(iosRatio, lecturer.getId(), new PagerInfo());
            map.put("recommends", recommends);
        }else {
            map.put("recommends", new ArrayList<>());
        }
        return ResultBody.success(map);
    }

    /**
     * yes
     * 首页搜索
     */
    @RequestMapping(value = "/searchWeb")
    public ResultBody searchWeb(String keyWord, PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        if (ObjectUtils.isEmpty(keyWord)) {
            map.put("list", new ArrayList<>());
            return ResultBody.success(map);
        }

        SysConfig config = configservice.getByName("iosRatio");
        BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
        PqGrid pq = courseService.searchCourseWeb(iosRatio, keyWord, pagerInfo);
        map.put("list", pq);
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }


    /**
     * yes
     * 首页搜索讲师
     */
    @RequestMapping(value = "/searchLecturerWeb")
    public ResultBody searchLecturerWeb(String keyWord, PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        if (ObjectUtils.isEmpty(keyWord)) {
            map.put("lecturerList", new ArrayList<>());
            return ResultBody.success(map);
        }
        PqGrid pq = lecturerService.searchLecturerWeb(keyWord,pagerInfo);
        map.put("lecturerList", pq);
        return ResultBody.success(map);
    }


    /**
     * yes
     * 讲师课程列表
     */
    @RequestMapping(value = "/lecturerCourseWeb")
    public ResultBody lecturerCourseWeb(String sortOrder, Long lecturerId, PagerInfo pagerInfo) {
        ApiAssert.notNull("参数不能为空", lecturerId, sortOrder);
        EntityMap map = new EntityMap();
        SysLecturer lecturer = lecturerService.getById(lecturerId);
        map.put("lecturer", lecturer);
        PqGrid pq = courseService.selectByLecturerWeb(lecturerId, sortOrder, pagerInfo);
        if (pq.getRows().size() < 1) {
            map.put("lists", new ArrayList<>());
            return ResultBody.success(map);
        }
        map.put("lists", pq);
        map.put("isVip", 0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if(ObjectUtils.isNotEmpty(openUserAuth)){
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            map.put("isVip", vip);
        }
        return ResultBody.success(map);
    }

    /**
     * 课程详情
     */
    @RequestMapping(value = "/courseDetail")
    public ResultBody courseDetail(Long courseId, PagerInfo pagerInfo, String url) {
        ApiAssert.notNull("参数不能为空", courseId);
        EntityMap detail = new EntityMap();
        Long accountInfoId = null;
        detail.put("isVip",0);
        OpenUserAuth openUserAuth = OpenHelper.getUserAuth();
        if (ObjectUtils.isNotEmpty(openUserAuth)) {
            accountInfoId = openUserAuth.getUserId();
            Integer vip = vipService.isVip(openUserAuth.getUserId());
            detail.put("isVip", vip);
        }
        putAliyun(detail);
        SysCourse course = courseService.getById(courseId);// 课程
        //课程浏览量
        if (ObjectUtil.isNotNull(course.getRecordNum())) {
            course.setRecordNum(course.getRecordNum() + 1);
        } else {
            course.setRecordNum(1);
        }
        courseService.saveOrUpdate(course);
        detail.put("recordNum",course.getRecordNum());
        SysLecturer lecturer = lecturerService.getById(course.getLecturerId());// 讲师
        // 详情
        EntityMap courseDetail = new EntityMap();
        courseDetail.put("isVipFree",course.getIsVipFree());    //Vip免费
        courseDetail.put("isFree",course.getIsFree());          //课程免费
        courseDetail.put("courseName", course.getCourseTitle());// 课程名称
        courseDetail.put("detail", course.getCourseContent());// 简介
        List<EntityMap> recommends = new ArrayList<>();
        if (ObjectUtils.isNotEmpty(lecturer)) {
            courseDetail.put("lecturerImg", lecturer.getLecturerImg());// 讲师头像
            courseDetail.put("lecturerName", lecturer.getLecturerName());// 讲师名称
            courseDetail.put("lecturerContent", lecturer.getContent());// 讲师简介
            SysConfig config = configservice.getByName("iosRatio");
            BigDecimal iosRatio = new BigDecimal(config.getConfigVal());
            recommends = courseService.selectByLecturer(iosRatio, String.valueOf(lecturer.getId()), new PagerInfo());
        } else {
            courseDetail.put("lecturerImg", "");// 讲师头像
            courseDetail.put("lecturerName", "");// 讲师名称
            courseDetail.put("lecturerContent", "");// 讲师简介
        }
        detail.put("recommends", recommends);
        courseDetail.put("coursePrice", course.getCoursePrice());
        courseDetail.put("courseId", course.getId());
        courseDetail.put("courseImage", course.getCourseImage());
        courseDetail.put("iosPrice", course.getIosPrice());
        detail.put("courseUrl", course.getCourseUrl());// 课程视频
        detail.put("courseDetail", courseDetail);// 课程详情
        // 目录
        List<Map<String, Object>> oneList = catalogService.selectOne(courseId);
        if (ObjectUtils.isNotEmpty(oneList)) {
            Integer one = 1;
            for (Map<String, Object> cl : oneList) {
                List<EntityMap> twoList = catalogService.selectTwo2(cl.get("id").toString(),
                    course.getCourseTitle(), course.getCourseImage());
                Integer two = 1;
                /*for(EntityMap twoCatalog : twoList){
                    twoCatalog.put("cataLogNo", one+"."+two);
                    ++two;
                }*/
                cl.put("twoList", twoList);
                ++one;
            }
        }
        detail.put("catalog", oneList);
        //微信二维码分享
        String QRCode = ZXingCode.getLogoQRCode(url, "", "");
        detail.put("QRCode", QRCode);
        detail.put("urlShare", url);
        String content = course.getCourseContent().replaceAll("<[.[^>]]*>", "").replaceAll("&nbsp;", "");
        if (content.length() > 100) {
            content = content.substring(0, 100) + "...";
        }
        detail.put("content", content);
        // 评论
        Integer replyNum = commentService.firstCommentNum(courseId);
        detail.put("replyNum", replyNum);
        List<EntityMap> replysOne = commentService.selectByCourse(courseId.toString(), pagerInfo, 1);// 课程的一级评论
        for (EntityMap one : replysOne) {
            one.put("nickName", Convert.unicodeToStr(one.get("nickName")));
            one.put("commentContent", Convert.unicodeToStr(one.get("commentContent")));
            //one.put("createDate", DateUtil.getDateTime(one.get("createDate"), DateUtil.MM月dd日HHmm));
            one.put("createDate", one.get("createDate"));
            // 查询用户是否点赞
            one.put("isThumbs", 0);
            if (ObjectUtils.isNotEmpty(accountInfoId)) {
                Long id = one.get("id");
                Integer isThumbs = colleconService.isCollecon(id, accountInfoId, 3, 2);
                one.put("isThumbs", isThumbs);
            }
            List<EntityMap> replysTwo = commentService.selectByCourse2(one.get("id").toString(), pagerInfo, 2, String.valueOf(accountInfoId));// 一级评论的二级级评论
            for (EntityMap two : replysTwo) {
                //two.put("createDate", DateUtil.getDateTime(two.get("createTime"), DateUtil.MM月dd日HHmm));
                two.put("commentContent", Convert.unicodeToStr(two.get("commentContent")));
                two.put("nickName", Convert.unicodeToStr(two.get("nickName")));
                two.put("createDate", two.get("createTime"));
            }
            one.put("replysTwo", replysTwo);
            Integer thumbs = colleconService.countByTarget(one.get("id").toString(), 2);
            one.put("thumbs", thumbs);
        }
        detail.put("replys", replysOne);
        detail.put("userId", "");
        // 是否收藏/购买
        if (ObjectUtils.isEmpty(accountInfoId)) {// 未登录用户关注/购买为否
            detail.put("isCollecon", 0);
            detail.put("isBuy", 0);
            return ResultBody.success(detail);
        }
        detail.put("userId", accountInfoId);
        BigDecimal coursePrice = course.getCoursePrice();
        Integer isBuy;
        if (coursePrice.compareTo(BigDecimal.ZERO) <= 0) {
            //免費课程
            isBuy = 1;
        } else {
            isBuy = courseapplyService.isApply(courseId, accountInfoId, 1);// 是否购买
            if (isBuy == 0) {
                Integer vip = vipService.isVip(openUserAuth.getUserId());
                //判断是否是VIP
                if (vip > 0) {
                    Integer vipFree = course.getIsVipFree();
                    if (vipFree.equals(0)) {
                        isBuy = 1;
                    }
                }
            } else {
                isBuy = 1;
            }

        }
        detail.put("isBuy", isBuy);//是否购买
        Integer isCollecon = colleconService.isCollecon(courseId, accountInfoId, 1, 1);// 是否收藏
        detail.put("isCollecon", 0);
        if (isCollecon > 0) {
            detail.put("isCollecon", 1);
        }
        // 添加观看记录
        SysHistory history = historyService.findByUser(accountInfoId.toString(), courseId.toString());
        if (ObjectUtils.isNotEmpty(history)) {
            history.setCreateTime(new DateTime());
            historyService.saveOrUpdate(history);
        } else {
            history = new SysHistory();
            history.setUserId(accountInfoId.toString());
            history.setCourseId(courseId.toString());
            historyService.save(history);
        }
        return ResultBody.success(detail);
    }

    /**
     * yes
     * vip页面
     */
    @RequestMapping(value = "/vipPageWeb")
    public ResultBody vipPageWeb(HttpServletResponse response) {
        EntityMap map = new EntityMap();
        List<Map<String, Object>> list = vipTypeService.selectAllVip();
        for (Map<String, Object> vip : list) {
            Long id = (Long) vip.get("id");
            List<SysVipconfig> vipconfig = vipconfigService.selectByVip(id);
            vip.put("vipconfig", vipconfig);
        }
        map.put("list", list);
        Integer company = vipService.countVip(1);
        Integer person = vipService.countVip(2);
        map.put("company", company);
        map.put("person", person);
        return ResultBody.success(map);
    }

    /**
     * 银联
     */
    @RequestMapping(value = "/unnpay")
    public ModelAndView unnpay(HttpServletResponse response, String result) throws IOException {
        System.out.println(result);
        String port = result.replaceAll(" ;", "\",\"").replaceAll("=", "\":\"");
        port = "{\"" + port + "\"}";
        System.out.println(port);
        JSONObject jsonobj = JSONUtil.parseObj(port);
        String outTradeNo = jsonobj.getStr("REFORD");
        Order order = orderService.findByNo(outTradeNo);
        order.setOrderStatus(OrderStatusEnum.finish);
        orderService.update(order);
//        ModelAndView mv = new ModelAndView("redirect:http://120.79.205.116:81/#/success");
        ModelAndView mv = new ModelAndView("redirect:http://web.cbstudy.com/#/success");
        return mv;
    }

    /**yes
     * 常见问题(帮助中心)
     */
    @PostMapping(value = "/issuePageWeb")
    public ResultBody issuePage(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid pq = htmlService.selectListWeb(pagerInfo);
        map.put("questions", pq);
        return ResultBody.success(map);
    }

    /**yes
     * 常见问题(帮助中心详情)
     */
    @PostMapping(value = "/issuePageDetail")
    public ResultBody issuePageDetail(Long issueId) {
        EntityMap map = new EntityMap();
        SysHtml question  = htmlService.getById(issueId);
        map.put("issue", question);
        return ResultBody.success(map);
    }

    /**
     * 新闻列表
     */
    @PostMapping(value = "/newsList")
    public ResultBody newsList(PagerInfo pagerInfo) {
        EntityMap map = new EntityMap();
        PqGrid newsList = getNews(pagerInfo);
        map.put("newsList", newsList);
        return ResultBody.success(map);
    }

    /**
     * 新闻详情
     */
    @PostMapping(value = "/newsDetail")
    public ResultBody newsDetail(Long newsId) {
        EntityMap map = new EntityMap();
        SysMessage news  = messageService.getById(newsId);
        map.put("news", news);
        return ResultBody.success(map);
    }

    private PqGrid getNews(PagerInfo pagerInfo) {
        CriteriaQuery cq = new CriteriaQuery(pagerInfo);
        cq.select("id,messageTitle,updateTime,createTime,newsImg,summary");
        cq.eq("messageType",3);
        cq.orderByAsc("sortOrder");
//        cq.select("ms.id,ms.messageType,ms.messageStatus,ms.targetId,ms.createTime,'订单支付成功提醒' orderTitle,ord.orderBody,ord.payDate,ord.id orderId");
//        cq.eq("ms.messageType", messageType);
//        cq.eq("ms.userId", userId);
//        cq.createAlias("order", "ord");
//        cq.orderByDesc("ms.createTime");
        return messageService.pageList(cq);
    }



    public void putAliyun(EntityMap map) {
        map.put("akid", configservice.getByName("AccessKeyId").getConfigVal());
        map.put("akSecret", configservice.getByName("AccessKeySecret").getConfigVal());
        map.put("token", configservice.getByName("SecurityToken").getConfigVal());
    }

}
